from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional
import os
# Our official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py)
from cozepy import COZE_CN_BASE_URL
coze_api_token = 'pat_HhhITxF8UzuAOaUTTEJHt1alaUEmKczxPks2G6Ic6hUnJIfXiiYwOd4MUY8RZ9iw'
# Get an access_token through personal access token or oauth.
# coze_api_token = 'cztei_l7yJuemXi8XAyOX4SaKg6RzyFZWflSm2XATxDmPSaYW9Uas51DE5U2PtM7Pa7Iva4'
# The default access is api.coze.com, but if you need to access api.coze.cn,
# please use base_url to configure the api endpoint to access
coze_api_base = COZE_CN_BASE_URL

from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType  # noqa

# Init the Coze client through the access_token.
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)

# Create a bot instance in Coze, copy the last number from the web link as the bot's ID.
bot_id = '7569489764324720640'

# 创建API路由器
coze_api = APIRouter()

class ChatRequest(BaseModel):
    user_id: str
    question: str

@coze_api.post("/chat")
async def chat_with_coze(request: ChatRequest):
    """
    与Coze机器人聊天的接口
    """
    try:
        full_response = ""
        # Call the coze.chat.stream method to create a chat. The create method is a streaming
        # chat and will return a Chat Iterator. Developers should iterate the iterator to get
        # chat event and handle them.
        for event in coze.chat.stream(
            bot_id=bot_id,
            user_id=request.user_id,
            additional_messages=[
                Message.build_user_question_text(request.question),
            ],
        ):
            if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
                full_response += event.message.content

            if event.event == ChatEventType.CONVERSATION_CHAT_COMPLETED:
                return {
                    "status": "success",
                    "response": full_response,
                    "token_usage": event.chat.usage.token_count
                }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Chat failed: {str(e)}")